package com.ocom.wxapi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.entity.human.EntityBizLeaveApply;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.activiti.HandleTasksRequest;
import com.ocom.common.request.activiti.PendingTasksRequest;
import com.ocom.common.request.activiti.ProcessInfoRequest;
import com.ocom.common.request.ugcapi.GzhUserLeaveList;
import com.ocom.common.request.web.CommonPidVo;
import com.ocom.common.request.wx.HandleApplyRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.PageListResult;
import com.ocom.common.vo.activiti.IncompleteTaskVO;
import com.ocom.common.vo.activiti.PageResultVo;
import com.ocom.common.vo.activiti.SearchFlowVo;
import com.ocom.wxapi.client.ActivitiClientService;
import com.ocom.wxapi.client.CompanyClientService;
import com.ocom.wxapi.client.HumanClientService;
import com.ocom.wxapi.vo.WxIncompleteTaskVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@RestController
@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/apply")
public class ApplyController {

    @Autowired
    ActivitiClientService activitiClientService;

    @Autowired
    HumanClientService humanClientService;

    @Autowired
    CompanyClientService companyClientService;

    private final String leaveKey  = "leave-apply";


    //列表
    @PostMapping("/list")
    public Result list(@Valid CommonPidVo request){
        PendingTasksRequest pendingTasksRequest = new PendingTasksRequest();
        pendingTasksRequest.setUserId("2");
        if(request.getPId()!=null){
            pendingTasksRequest.setUserId(request.getPId().toString());
        }
        pendingTasksRequest.setApplyKey(leaveKey+"-"+request.getComId());
        Result<PageResultVo<IncompleteTaskVO>> result = activitiClientService.pendingTasks(pendingTasksRequest);
        if(result.getCode() !=200 ){
            return result;
        }
        if(result.getData().getTotal()==0){
            return ResultUtil.success(new ArrayList<>());
        }

        List<Integer> ids =new ArrayList<>();

        for(int i=0; i < result.getData().getRows().size(); i++){
            IncompleteTaskVO incompleteTaskVO = result.getData().getRows().get(i);
            int sub = incompleteTaskVO.getBusinessKey().lastIndexOf(":");
            sub++;
            Integer id = Integer.valueOf(incompleteTaskVO.getBusinessKey().substring(sub));
            ids.add(id);
            incompleteTaskVO.setApplyId(id);
            result.getData().getRows().set(i,incompleteTaskVO);
        }


        GzhUserLeaveList gzhUserLeaveList=new GzhUserLeaveList();
        gzhUserLeaveList.setComId(request.getComId());
        gzhUserLeaveList.setIds(ids);
        Result<PageListResult<EntityBizLeaveApply>> listResultResult =  companyClientService.leavelApplyList(gzhUserLeaveList);

        List<WxIncompleteTaskVO> jsonObjectList =new ArrayList<>();

        for(IncompleteTaskVO incompleteTaskVO:result.getData().getRows()){
            WxIncompleteTaskVO wxIncompleteTaskVO =JSON.parseObject(JSON.toJSONString(incompleteTaskVO), WxIncompleteTaskVO.class);
            wxIncompleteTaskVO.setTaskId(incompleteTaskVO.getId());
            for (EntityBizLeaveApply entityBizLeaveApply : listResultResult.getData().getList()){
                if(incompleteTaskVO.getApplyId().equals(entityBizLeaveApply.getId())){

                    wxIncompleteTaskVO.setId(entityBizLeaveApply.getId().toString());
                    wxIncompleteTaskVO.setComId(entityBizLeaveApply.getComId());
                    wxIncompleteTaskVO.setPId(entityBizLeaveApply.getPId());
                    wxIncompleteTaskVO.setStatus(entityBizLeaveApply.getStatus());
                    wxIncompleteTaskVO.setType(entityBizLeaveApply.getType());
                    wxIncompleteTaskVO.setReason(entityBizLeaveApply.getReason());
                    wxIncompleteTaskVO.setPic(entityBizLeaveApply.getPic());
                    wxIncompleteTaskVO.setDays(entityBizLeaveApply.getDays());
                    wxIncompleteTaskVO.setStartTime(entityBizLeaveApply.getStartTime());
                    wxIncompleteTaskVO.setEndTime(entityBizLeaveApply.getEndTime());
                    wxIncompleteTaskVO.setCreateTime(entityBizLeaveApply.getCreateTime());
                    wxIncompleteTaskVO.setUpdateTime(entityBizLeaveApply.getUpdateTime());
                    wxIncompleteTaskVO.setDefKey(entityBizLeaveApply.getDefKey());
                    wxIncompleteTaskVO.setActivitiKey(entityBizLeaveApply.getActivitiKey());
                    wxIncompleteTaskVO.setTitle(entityBizLeaveApply.getTitle());

                    break;
                }
            }
            jsonObjectList.add(wxIncompleteTaskVO);
        }
        return ResultUtil.success(jsonObjectList);
    }

    //审批
    @PostMapping("/handle")
    public Result handle(@Valid HandleApplyRequest request){

        if(request.getStatus()==null || request.getStatus()<1 || request.getStatus()>2){
            return ResultUtil.error(ResultEnum.Err_203);
        }

        EntityBizLeaveApply entityBizLeaveApply=new EntityBizLeaveApply();
        entityBizLeaveApply.setComId(request.getComId());
        entityBizLeaveApply.setId(request.getId().longValue());

        Result<EntityBizLeaveApply>  result = companyClientService.leavelApplyOne(entityBizLeaveApply);

        HandleTasksRequest handleTasksRequest =new HandleTasksRequest();
        handleTasksRequest.setComment(request.getComment());
        handleTasksRequest.setTaskId(request.getTaskId());
        handleTasksRequest.setUserId(request.getPId().toString());
        handleTasksRequest.getParams().put("status",request.getStatus());
        handleTasksRequest.getParams().put("days",result.getData().getDays());
        handleTasksRequest.getParams().put("type",result.getData().getType());

        Result<HashMap> mapResult = activitiClientService.handleTask(handleTasksRequest);

        if(mapResult.getCode()==200){
            if(!(Boolean) mapResult.getData().get("handle")){
                return ResultUtil.error(ResultEnum.Err_2009);
            }
            if((Boolean) mapResult.getData().get("exit")){
                entityBizLeaveApply.setStatus(request.getStatus());
                companyClientService.updateLeavelApply(entityBizLeaveApply);
            }
            return mapResult;
        }

        log.info("审批异常 【{}】",mapResult);
        return ResultUtil.error(ResultEnum.Err_2009);
    }

    // 详情
    @PostMapping("/detail")
    public Result leaveApplyDeatil(@Valid ProcessInfoRequest request){

        String key =leaveKey +"-"+request.getComId();

        Result<List<SearchFlowVo>> result1 = activitiClientService.getProcessInfo(key,key+":"+request.getComId()+":"+request.getId());
        if(result1.getCode()!=200){
            return result1;
        }

        JSONObject jsonObject=new JSONObject();
        jsonObject.put("comId",request.getComId());
        jsonObject.put("status",0);
        jsonObject.put("page",1);
        jsonObject.put("size",500);
        //管理员
        Result<PageListResult<EntityMngUserInfo>>  mngUserList = humanClientService.getMngUserInfo(jsonObject);

        //list转map
        Map<String, String> stringMap = mngUserList.getData().getList().stream().collect(Collectors.toMap(e -> e.getId().toString(),
                e -> e.getUserName(),
                (e1, e2) -> e1));

        for (int i = 0; i < result1.getData().size(); i++) {
            SearchFlowVo searchFlowVo = result1.getData().get(i);
            if(null!=searchFlowVo.getUserId()){
                if(!searchFlowVo.getUserId().contains(":")){
                    if(stringMap.containsKey(searchFlowVo.getUserId())){
                        searchFlowVo.setUserId(stringMap.get(searchFlowVo.getUserId()));
                    }
                }else{
                    searchFlowVo.setUserId("发起人");
                }
            }
            if(searchFlowVo.getApprovalUser().size()>0){
                for (int j = 0; j < searchFlowVo.getApprovalUser().size(); j++) {
                    String uid = searchFlowVo.getApprovalUser().get(j);
                    if(stringMap.containsKey(uid)){
                        searchFlowVo.getApprovalUser().set(j,stringMap.get(uid));
                    }
                }
            }
            result1.getData().set(i,searchFlowVo);
        }
        return ResultUtil.success(result1.getData());
    }

}
